#!/usr/bin/env python
#coding:utf-8

import sys
import datetime
import json
import requests
#import MySQLdb

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

'''
# 读取mysql的配置文件
def get_mysql_config():
	conf = {}
	conf['ip']      = '192.168.5.253'
	conf['port']    = '3324'
	conf['user']    = 'work_w'
	conf['passwd']  = '12345qwert'
	conf['db']      = 'athena_baike'
	conf['charset'] = 'utf8'
	return conf

# 初始化mysql连接,并返回
def init_mysql_db(conf):    #mysql_ip, mysql_user, mysql_passwd, mysql_db, mysql_port):
	db = MySQLdb.connect(host=conf['ip'], port=int(conf['port']),
	                     user=conf['user'], passwd=conf['passwd'],
	                     db=conf['db'], charset=conf['charset'])
	return db


# 执行sql语句并返回结果
def db_execute_result(cursor, sql):
	if cursor is None or sql is None:
		return None
	
	try:
		cursor.execute(sql)
		data = cursor.fetchall()
		return data
	except:
		print "Error: unable to fecth data, sql=[%s]" % sql
		return None


# 执行sql语句并返回结果
def db_execute_commit(db, cursor, sql):
	if db is None or cursor is None or sql is None:
		return None
	
	try:
		data = cursor.execute(sql)
		db.commit()
		return data
	except:
		print "Error: unable to fecth data, sql=[%s]" % sql
		db.rollback()
		return None

'''
# def get_song_info(cursor, song_dict):
#
# 	res_ids = commtools.fun_list_to_str(song_dict.keys())
# #	print res_ids
# 	sql = '''
# 	SELECT res_globalid, si_globalid, si_name, si_main_artist_id, si_main_artist_name
# 	FROM quku_song_info AS qs, quku_resource AS qr
# 	WHERE qr.res_entity_id = qs.si_globalid AND qr.res_globalid IN %s;
# 	''' % res_ids
# 	results = db_execute_result(cursor, sql)
# 	if results is None or len(results) == 0:
# 		return None
#
# 	ids = []
# 	for row in results:
# 		song_dict[row[0]] = row
# 		ids.append(row)
#
# #	commtools.pretty_dict(song_dict)
# 	return song_dict


def get_song_info(res_id):
	url = 'http://192.168.5.23:7070/song/getinfo?ci=%d' % (res_id)
	res = requests.get(url)
	if res.status_code != requests.codes.ok:
		return []
	
	res.encoding = 'utf8'
	jres = json.loads(res.text)
	if jres['errcode'] != 0:
		return []
	
	data = jres['data']
	return [
		data['title'],
		data['author'],
		data['album_title'],
		data['all_rate'],
		res_id,
	]
	
	
def load_rank_file(file_in):

	fin = open(file_in)
	rank_all = json.load(fin)
	print rank_all["billboardNo"]
	
	songinfos = []
	for i in rank_all["rows"]:
		info = get_song_info(i['song_id'])
		print u'%3d: %-6d' % (i['rank'], i['trust_count']),
		if len(info) == 0:
			print i['song_id']
		else:
			print 'songid=%-10d song=%-10s artist=%-10s album=%-10s' % (info[4], info[0], info[1], info[2])
	
	# db = init_mysql_db(get_mysql_config())
	# cursor = db.cursor()
	# song_dict = get_song_info(cursor, song_dict)
	#
	# for i in rank_all["rows"]:
	# 	info = song_dict[ i['song_id'] ]
	# 	print u'%d: song=%s, artist=%s, hot=%d' % (i['rank'], info[2], info[4], i['trust_count'])

	
	fin.close()

#   logging.info('========STARTUP pid=[%d] cmd=%s ========' % (os.getpid(), sys.argv))
def main():
#	commtools.init_log()

	file_in = sys.argv[1] if len(sys.argv) > 1 else 'd:/99.temp/netsong.20190214'
	load_rank_file(file_in)


if __name__ == "__main__":
	'''
	argc = len(sys.argv)
	if 2 > argc or ('-v' == sys.argv[1] or '-h' == sys.argv[1]):
		print '\n\t command line is like \'python %s file\'\n' % __file__
	else:
		main()
	'''
	main()


'''
	LiangQuan, 2019/02/13,
	取出指定的榜单文件，通过mfdapi接口获取榜单歌曲的信息，并显示
	
'''
